//
//  BBMouseFakerController.m
//  BBTouch
//
//  Created by ben smith on 8/22/08.
//  Copyright 2008 __MyCompanyName__. All rights reserved.
//

#import "BBMouseFakerController.h"
#import "BBScreenSelectionView.h"
#import "BBTUIOCursor.h"


@implementation BBMouseFakerController

@synthesize active;

-(void)awakeFromNib
{
	self.active = NO;
	fakeMouseID = -1;
}

-(void)setCursors:(NSArray*)anArray
{
	if (!active) return;

	if (fakeMouseID < 0) {
		// then this is the first i have seen of these blobs
		// grab the very first one, it is going to be our mouse
		if ([anArray count] < 1) return;
		fakeMouseID = [[anArray objectAtIndex:0] cursorID];
		lastPoint = [self fakeMousePointInSelectedScreenWithCursor:[anArray objectAtIndex:0]];
		CGError err = CGPostMouseEvent (NSPointToCGPoint(lastPoint), 1, 1, 1);
		return;
	}
	
	// if we are here then it is either a drag or an up
	BBTUIOCursor * fakeMouseCursor = nil;
	for (BBTUIOCursor* cursor in anArray) {
		if (fakeMouseID == [cursor cursorID]) {
			// then this is the one we care about
			fakeMouseCursor = cursor;
			break;
		}
	}
	if (fakeMouseCursor == nil) {
		// then the blob left, mouse up
		CGError err = CGPostMouseEvent (NSPointToCGPoint(lastPoint), 1, 1, 0);		
		fakeMouseID = -1;
		return;
	}


	lastPoint = [self fakeMousePointInSelectedScreenWithCursor:fakeMouseCursor];
	CGError err = CGPostMouseEvent (NSPointToCGPoint(lastPoint), 1, 1, 1);		

}



-(NSPoint)fakeMousePointInSelectedScreenWithCursor:(BBTUIOCursor*)cursor
{
	NSRect screenFrame = [screenSelector.chosenScreen frame];
	NSRect mainScreenFrame = [[NSScreen mainScreen] frame];

	float menuY = NSMaxY(mainScreenFrame);
	float yDiff = menuY - NSMaxY(screenFrame);
	// now scale the point into our rectangle
	NSLog(@"%@ %f %f" ,NSStringFromRect(screenFrame),menuY,yDiff);
	
	NSPoint mouse = [cursor position];
	mouse.x *= NSWidth(screenFrame);
	mouse.y *= NSHeight(screenFrame);

	mouse.x += screenFrame.origin.x;
	mouse.y += yDiff;
	NSLog(@"%@",NSStringFromPoint(mouse));
	return mouse;
}

@end
